<?php
namespace Cms\Controller;
use Think\Controller;
class ApiController extends Controller {

	public static $WAP;//CMS全局静态变量
	public $AJAX_TYPE = '';
	
	protected function _initialize(){
		//刷新全局会员配置
		self::$WAP['vipset']=$this->checkVipSet();
		//刷新全局商城配置
//    	self::$WAP['shopset']=$_SESSION['WAP']['shopset']=$this->checkShopSet();
//    	$this->log();

		if(isset($_GET[C('VAR_JSONP_HANDLER')])) $this->AJAX_TYPE = 'JSONP';
	}
	
	/**
	 * @package 接口日志
	 * @param userid:用户标识
	 * @param send_data:发送数据
	 * @param return_data:接口调用结果
	 * @param remark:操作描述（如操作内容等）
	 */
	public function log(){
		$event = MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
		$data=I('param.');
		$remark = json_encode($data);
		$adddata = array('event'=>$event, 'create_date'=>date("Y-m-d H:i:s"), 'clientip'=>get_client_ip());
		if($data['userid']) $adddata['userid'] = $data['userid'];
		if($data['send_data']) $adddata['send_data'] = is_array($data['send_data'])?json_encode($data['send_data']):$data['send_data'];
		if($data['return_data']) $adddata['return_data'] = is_array($data['return_data'])?json_encode($data['return_data']):$data['return_data'];
		if($data['remark']) $adddata['remark'] = $data['remark'];
		$result = array('status'=>0);
		$res = M("event_log")->add($adddata);
		if($res) {
			$result['status'] = 1;
			$result['msg'] = '操作成功';
		} else $result['msg'] = '操作失败';
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}

	//获取消息
	public function get_message(){
		$userid = I("userid");
		$result = array('status'=>0);
		if($userid){
			$p=I("page");
			$p=$p?$p:1;
			$psize=I("pagesize");
			$psize=$psize?$psize:20;
			$type=I("type_id");//1为弹窗提示、2为左边公告、3为右上角、4为消息、5为帮助、6为规则4、7为文件里的第七种
			if(in_array($type,array(1,2,3,4,5,6,7))){
				$where = array('userid'=>$userid, 'type_id'=>$type);
			}else{
				$where = "userid='$userid' OR userid = ''";
			}
			$field = "*";
			$info = M("message","t_")->where($where)->field($field)->page($p,$psize)->order("modify_date DESC")->select();
			$result['info'] = $info;
			$result['status'] = 1;
		}else{
			$result['msg'] = "参数错误！";
		}
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
	//充值等记录日志
	public function rechange_log(){
		$userid = I("userid");
		$openid = I("openid");
		$type = I("typeid");//日志类型 1获取注册验证码，2会员签到，3会员登陆，4会员注册，5消息读取（每条消息只记录一次），6充值卡充值，7在线充值（status0请求1成功），8购买商品，10房卡充值，11元宝充值
		$desc = I("remark");
		$money = I("money");
		$score = I("score");
		$exp = I("exp");
		$gems = I("gems");
		$coins = I("coins");
		$status = I("status");//执行成功与否
		$orderid = I("orderid");
		$result = array('status'=>0);
		if(($userid||$openid) && in_array($type, array('10','11'))){
			$mvip=M('vip');
			if($openid){
				$userinfo = $mvip->where(array('openid'=>$openid))->find();
				$userid = $userinfo['id'];
			}else{
				$userinfo = $mvip->where(array('id'=>$userid))->find();
			}
			if($status=='1'){//充值成功 修改用户表增加点数
				$vipdata = array();
				switch ($type){
					case '10': $vipdata['gems'] = $userinfo['gems']+$gems; break;
					case '11': $vipdata['coins'] = $userinfo['coins']+$coins; break;
				}
				$res = $mvip->where(array('id'=>$userid))->save($vipdata);
				if(!$res){
					$result['status'] = 0;
					$result['msg'] = "操作失败！";
					$this->ajaxReturn($result, $this->AJAX_TYPE);
				}
			}
			$m = M("Vip_log");
			$data = array('ip'=>get_client_ip(), 'vipid'=>$userid, 'openid'=>$userinfo['openid'], 'nickname'=>$userinfo['nickname'], 'mobile'=>$userinfo['mobile'], 'ctime'=>time());
			if($money) $data['money'] = $money;
			if($score) $data['score'] = $score;
			if($exp) $data['exp'] = $exp;
			if($gems) $data['gems'] = $gems;
			if($coins) $data['coins'] = $coins;
			if(!$desc){
				switch ($type){
					case '10': $desc = '会员充值房卡 + '.$gems; break;
					case '11': $desc = '会员充值元宝 + '.$coins; break;
				}
			}
			if($orderid) $data['remark'] = $orderid;
			$data['event'] = $desc;
			$data['status'] = $status ? 1 : 0;
			$data['type'] = $type;
			if($m->add($data)){
				$result['status'] = 1;
			}else{
				$result['status'] = 0;
				$result['msg'] = "操作失败！";
			}			
		}else{
			$result['msg'] = "参数错误！";
		}
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
	
	//返回全局配置
	public function checkSet(){
		$set=M('Set')->find();
		return $set?$set:utf8error('系统全局设置未定义！');
	}
	
	//返回全局配置
	public function checkShopSet(){
		$set=M('shop_set')->find();
		return $set?$set:utf8error('商城设置未定义！');
	}
	//返回VIP配置
	public function checkVipSet(){
		$set=M('vip_set')->find();
		return $set?$set:utf8error('会员设置未定义！');
	}
	
	public function getlevel($exp) {
		$data=M('vip_level')->order('exp')->select();
		if ($data) {
			$level;
			foreach ($data as $k=>$v) {
				if ($k+1==count($data)) {
					if ($exp>=$data[$k]['exp']) {
						$level['levelid']=$data[$k]['id'];
						$level['levelname']=$data[$k]['name'];
					}
				} else {
					if ($exp>=$data[$k]['exp'] && $exp<$data[$k+1]['exp']) {
						$level['levelid']=$data[$k]['id'];
						$level['levelname']=$data[$k]['name'];
					}
				}
			}
		} else {
			return false;
		}
		return $level;
	}

	private function _logfx($level,$user,$old,$mvip){
		$str = $grade = "";
		$arr = array('1'=>'一级','2'=>'二级','3'=>'三级');
		if($level>1) {
			$grade .= "_".$level;
		}

		$tj_score=self::$WAP['vipset']['tj_score'.$grade];
		$tj_exp=self::$WAP['vipset']['tj_exp'.$grade];
		$tj_money=self::$WAP['vipset']['tj_money'.$grade];
		$tj_gems=self::$WAP['vipset']['tj_gems'.$grade];
		if($tj_score|| $tj_exp || $tj_money || $tj_gems){
			$msg="推荐新用户[下线]奖励(".$arr[$level].")：<br>新用户：".$user['nickname']."<br>奖励内容：<br>";
			$mglog="获得新下线注册奖励:";
			if($tj_score){
				$old['score']=$old['score']+$tj_score;
				$msg=$msg.$tj_score."个积分<br>";
				$mglog=$mglog.$tj_score."个积分；";
			}
			if($tj_exp){
				$old['exp']=$old['exp']+$tj_exp;
				$msg=$msg.$tj_exp."点经验<br>";
				$mglog=$mglog.$tj_exp."点经验；";
			}
			if($tj_money){
				$old['coins']=$old['coins']+$tj_money;
				$msg=$msg.$tj_money."元宝<br>";
				$mglog=$mglog.$tj_money."元宝；";
			}
			if($tj_gems){
				$old['gems']=$old['gems']+$tj_gems;
				$msg=$msg.$tj_money."房卡<br>";
				$mglog=$mglog.$tj_gems."房卡；";
			}
			$msg=$msg."此奖励已自动打入您的帐户！感谢您的支持！";
			$rold=$mvip->save($old);
			if(FALSE !== $rold){
				$d = date("Y-m-d H:i:s");
				$data_msg['userid']=$old['id'];
				$data_msg['user_name']=$old['nickname'];
				$data_msg['title']="你获得一份推荐奖励(".$arr[$level].")！";
				$data_msg['msg']=$msg;
				$data_msg['type_id']=4;
				$data_msg['version']=date("Ymd");
				$data_msg['create_date']=$d;
				$rmsg=M('message','t_')->add($data_msg);
				$data_mglog['vipid']=$old['id'];
				$data_mglog['nickname']=$old['nickname'];
				$data_mglog['xxnickname']=$user['nickname'];
				$data_mglog['msg']=$mglog;
				$data_mglog['ctime']=time();
				$rmglog=M('fx_log_tj')->add($data_mglog);
			}
		}
	}
	
	//登录用户 有无分享 做三级分销
	public function fx_user_register(){
		$user = I("param.");
		$result = array('status'=>0);
		if(!$user||!in_array($user['usertype'], array('0','1'))||($user['usertype']=='1'&&!$user['openid'])||(!$user['usertype']&&(!$user['account']||!$user['nickname']))){
			$result['msg'] = "参数错误";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		$openid = $user['openid'];//openid nickname sex province city country headimgurl privilege unionid shareuserid(分享链接的人) usertype(0是游客，1是微信登录)
		//容错，防止重复注册VIP
		$mvip=M('vip');
		if($user['usertype']=='1'){
			$vip=$mvip->where(array('openid'=>$openid,'usertype'=>'1'))->find();
		}else{
			$vip=$mvip->where(array('aliaccount'=>$user['account'],'nickname'=>$user['nickname'],'usertype'=>'0'))->find();
		}
		if($vip){			
			$result['msg'] = "会员已注册";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		//容错，防止ppid不存在
		if($user['shareuserid']){//有分享者 做分销
			$ppid = $user['shareuserid'];
//			$ppid=$_SESSION['oappid']?$_SESSION['oappid']:0;
//			$oasid=$_SESSION['oasid']?$_SESSION['oasid']:0;
	
			//处理父亲
			$old=$mvip->where(array('id'=>$ppid))->find();
			//dump($ppid);
			//dump($old);
			//die('系统调试！');
			if($old){
				$this->_logfx(1,$user,$old,$mvip);
				
				//三层上线追溯统计
				$old['total_xxlink']=$old['total_xxlink']+1;
				$r1=$mvip->save($old);
				if($old['pid']){
					$oldold=$mvip->where('id='.$old['pid'])->find();
					$oldold['total_xxlink']=$oldold['total_xxlink']+1;
					$r2=$mvip->save($oldold);
					$this->_logfx(2,$user,$oldold,$mvip);
					if($oldold['pid']){
						$oldoldold=$mvip->where('id='.$oldold['pid'])->find();
						$oldoldold['total_xxlink']=$oldoldold['total_xxlink']+1;
						$r3=$mvip->save($oldoldold);
						$this->_logfx(3,$user,$oldoldold,$mvip);
					}
				}
				//三层上线渠道追溯统计
				//									if($old['sid']){
				//										$mfxs=M('Fxs_user');
				//										$fx1=$mfxs->where('id='.$old['sid'])->find();
				//										$refx1=$mfxs->where('id='.$old['sid'])->setInc('total_xxlink',1);
				//										if($fx1['pid']){
				//											$fx2=$mfxs->where('id='.$fx1['pid'])->find();
				//											$refx2=$mfxs->where('id='.$fx1['pid'])->setInc('total_xxlink',1);
				//											if($fx2['pid']){
				//												$fx3=$mfxs->where('id='.$fx2['pid'])->find();
				//												$refx3=$mfxs->where('id='.$fx2['pid'])->setInc('total_xxlink',1);
				//											}
				//										}
				//									}
				//三层上线渠道不包含第一层
				//									if($old['sid']){
				
//				$mfxs=M('Fxs_user');
//				$fx1=$mfxs->where('id='.$old['sid'])->find();
//				$refx1=$mfxs->where('id='.$old['sid'])->setInc('total_xxlink',1);
//				if($fx1['pid']){
//					$fx2=$mfxs->where('id='.$fx1['pid'])->find();
//	
//					if($fx2['pid']){
//						$refx2=$mfxs->where('id='.$fx1['pid'])->setInc('total_xxlink',1);
//						$fx3=$mfxs->where('id='.$fx2['pid'])->find();
//						if($fx3['pid']){
//							$refx3=$mfxs->where('id='.$fx2['pid'])->setInc('total_xxlink',1);
//						}
//					}
//				}

			}
		}
		//强制渠道定义
		if($old['sid']){
			$data['sid']=$old['sid'];
		}else{
			$data['sid']=0;
		}
		//系统追入path
		if($old['id']){
			$data['pid']=$old['id'];
			$data['path']=$old['path'].'-'.$old['id'];
			$data['plv']=$old['plv']+1;
		}else{
			$data['pid']=0;
			$data['path']=0;
			$data['plv']=1;
		}
		
		if($user['openid']) $data['openid']=$user['openid'];
		if($user['nickname']) $data['nickname']=$user['nickname'];
		if($user['sex']) $data['sex']=$user['sex'];
		if($user['city']) $data['city']=$user['city'];
		if($user['province']) $data['province']=$user['province'];
		if($user['country']) $data['country']=$user['country'];
		if($user['headimgurl']) $data['headimgurl']=$user['headimgurl'];
		if($user['subscribe']) $data['subscribe']=$user['subscribe'];
		if($user['account']) $data['aliaccount']=$user['account'];
		if($user['name']) $data['name']=$user['name'];
		
//		if($user['usertype']=='1'){
//			$data['openid']=$user['openid'];
//			$data['nickname']=$user['nickname'];
//			$data['sex']=$user['sex'];
//			$data['city']=$user['city'];
//			$data['province']=$user['province'];
//			$data['country']=$user['country'];
//			$data['headimgurl']=$user['headimgurl'];
//			$data['subscribe']=$user['subscribe'];
//		}else{
//			$data['aliaccount']=$user['account'];
//			$data['name']=$user['name'];
//			$data['nickname']=$user['nickname'];
//		}
		$data['score']=self::$WAP['vipset']['reg_score'];
		$data['exp']=self::$WAP['vipset']['reg_exp'];
		$data['cur_exp']=self::$WAP['vipset']['reg_exp'];
		$data['coins']=self::$WAP['vipset']['reg_coins'];
		$data['gems']=self::$WAP['vipset']['reg_gems'];
		$level=$this->getLevel($data['exp']);
		$data['levelid']=$level['levelid'];
		$data['ctime']=time();
		$data['cctime']=time();
		//设置分销渠道
		// if(!self::$WAP['shopset']['vipfxneed']){
			$data['isfx']=1;
		// }
		$data['usertype'] = $user['usertype'];
		$rvip=$mvip->add($data);
		if($rvip){
			//赠送操作
//			if (self::$WAP['vipset']['isgift']) {
//				$gift=explode(",", self::$WAP['vipset']['gift_detail']);
//				$cardnopwd = $this->getCardNoPwd();
//				$data_card['type']=$gift[0];
//				$data_card['vipid']=$rvip;
//				$data_card['money']=$gift[1];
//				$data_card['usemoney']=$gift[3];
//				$data_card['cardno']=$cardnopwd['no'];
//				$data_card['cardpwd']=$cardnopwd['pwd'];
//				$data_card['status']=1;
//				$data_card['stime']=$data_card['ctime']=time();
//				$data_card['etime']=time()+$gift[2]*24*60*60;
//				$rcard=M('Vip_card')->add($data_card);
//			}
			//发送注册通知消息
			//记录日志
			$data_log['ip'] = get_client_ip();
			$data_log['vipid'] = $rvip;
			$data_log['ctime'] = time();
			$data_log['openid'] = $data['openid'];
			$data_log['nickname'] = $data['nickname'];
			$data_log['event'] = "会员注册";
			$data_log['score'] = $data['score'];
			$data_log['exp'] = $data['exp'];
			$data_log['type'] = 4;
			$rlog=M('Vip_log')->add($data_log);
			//正常处理完成，返回原链接
			$result['status'] = 1;
			$result['data'] = array('userid'=>$rvip);
			$result['msg'] = "用户注册成功";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}else{
			$result['msg'] = "用户注册失败";
			$this->ajaxReturn($result, $this->AJAX_TYPE);			
		}

	}
	
	//获取用户信息
	public function get_userinfo(){
		$result = array('status'=>0);
		$openid = I("openid");
		$userid = I("userid");
		if($openid||$userid){
			$mvip=M('vip');
			$userinfo = array();
			if($openid){
				$userinfo = $mvip->where(array('openid'=>$openid))->find();
			}else{
				$userinfo = $mvip->where(array('id'=>$userid))->find();
			}
			$result['status'] = 1;
			$result['data'] = $userinfo;
		}else{
			$result['msg'] = "参数错误";	
		}
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
	//充值订单处理
	public function rechange_order(){
		$result = array('status'=>0);
		$openid = I("openid");
		$userid = I("userid");
		$orderid = I("orderid");
		$act = I("act");
		$total_fee = I("total_fee");
		$typeid = I("typeid");
		$typevalue = I("typevalue");
		$return_param = I("return_param");
		$m = M("recharge_log");
		$orderinfo = array();
		if($act=='1'){//添加
			if(!$openid&&!$userid||!$orderid||!in_array($typeid,array(10,11))||!$typevalue||!$total_fee){
				$result['msg'] = "参数错误";
			}else{
				if($orderinfo = $this->_get_rechargeorder($orderid,$m)){
					$result['msg'] = "订单已存在";
				}else{
					$this->_get_user($openid,$userid);
					$result['status'] = $m->add(array('orderid'=>$orderid, 'userid'=>$userid, 'openid'=>$openid, 'total_fee'=>$total_fee, 'typeid'=>$typeid, 'typevalue'=>$typevalue, 'create_date'=>date("Y-m-d H:i:s")))?1:0;
					$orderinfo['openid'] = $openid;
					$orderinfo['userid'] = $userid;
					$orderinfo['typeid'] = $typeid;
					$orderinfo['typevalue'] = $typevalue;
				}
			}
		}elseif ($act=='2'){//更新
			if(!$orderid||!$return_param){
				$result['msg'] = "参数错误";
			}else{
				if(!$data = $this->_split_returnparam($return_param)){
					$result['msg'] = "参数错误";
				}else{
					if(!$orderinfo = $this->_get_rechargeorder($orderid,$m)){
						$result['msg'] = "订单不存在";
					}else{
						if($orderinfo['result_code']==''){
							$result['status'] = $m->where(array('orderid'=>$orderid))->save($data)?1:0;
							if($result['status']) $this->cz_get($orderinfo);
						}else{
							$result['msg'] = "订单已处理";
						}
					}
				}
			}
		}else{
			$result['msg'] = "参数错误";	
		}
		if($result['status']){
			$userinfo = array('openid'=>$orderinfo['openid'], 'userid'=>$orderinfo['userid'], 'typeid'=>$orderinfo['typeid'], 'typevalue'=>$orderinfo['typevalue']);
			$result['data'] = $userinfo;
		}else{
			if(!$result['msg']) $result['msg'] = "操作失败";
		}
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
	//充值获取积分或经验值（百分比）
	private function cz_get($rechargeOrder){
		$total_fee = round($rechargeOrder['total_fee']/100);		
		$data_vip['id']=$rechargeOrder['userid'];
		$data_vip['score']=array('exp','score+'.round($total_fee*self::$CMS['vipset']['cz_score']/100));
		$vip=M('Vip')->where('id='.$data_vip['id'])->find();
		if (self::$CMS['vipset']['cz_exp']>0) {
			$data_vip['exp']=array('exp','exp+'.round($total_fee*self::$CMS['vipset']['cz_exp']/100));
			$data_vip['cur_exp']=array('exp','cur_exp+'.round($total_fee*self::$CMS['vipset']['cz_exp']/100));
			$level=$this->getLevel($vip['cur_exp']+round($total_fee*self::$CMS['vipset']['cz_exp']/100));
			$data_vip['levelid']=$level['levelid'];
		}
		return M('vip')->save($data_vip);	
	}
	
	private function _get_user(&$openid,&$userid){
		$mvip=M('vip');
		if($openid){
			$userinfo = $mvip->where(array('openid'=>$openid))->find();
			$userid = $userinfo['id']?$userinfo['id']:0;
		}else{
			$userinfo = $mvip->where(array('id'=>$userid))->find();
			if($userinfo['openid']) $openid = $userinfo['openid'];
			else $openid = '';
		}
		return $userinfo;
	}
	
	private function _get_rechargeorder($orderid,$m){
		return $m->where(array('orderid'=>$orderid))->find();
	}
	
	private function _split_returnparam($return_param){
		if(stripos($return_param,'&amp;')!=false){
			$return_param = str_ireplace("&amp;","&",$return_param);
		}
		$params = explode("&",$return_param);//print_r($params);exit;
		$config = array("opstate"=>"result_code", "sysorderid"=>"transaction_id", "systime"=>"time_end", "attach"=>"attach", "msg"=>"result_msg");
		$data = array();
		if($return_param) $data["return_param"] = $return_param;
		foreach ($params as $val){
			$arr = explode("=", $val);
			if(isset($config[$arr[0]])){
				if($arr[0]=='systime'||$arr[0]=='msg'){
					$encode = mb_detect_encoding(urldecode($arr[1]), array('ASCII','GB2312','GBK','UTF-8'));
					$arr[1] = iconv($encode, 'UTF-8', urldecode($arr[1]));
				}
				$data[$config[$arr[0]]] = $arr[1];
			}
		}//print_r($data);exit;
		return $data;
	}
	
	//创建房间
	public function create_rooms(){
		$result = array('status'=>0);
		$userid = I("userid");
		$uuid = I("uuid");
		$roomid = I("room_id");
		$is_join = I("is_join");
		$base_info = I("base_info");
		$ip = I("ip");
		$port = I("port");
		$account = I("account");
		if(!$userid||!$roomid||!$uuid||!$base_info){
			$result['msg'] = "参数错误";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		$userinfo = $this->_get_user($openid,$userid);
		if(!$userinfo){
			$result['msg'] = "用户不存在";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}elseif (!$userinfo['status']){
			$result['msg'] = "用户被禁用";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		if(!$userinfo['isjx']){//不是经销商
			$is_join = 1;
		}else {
			$is_join = $is_join==1?1:0;
		}
		$m = M("rooms","t_");
		if($m->where(array('id'=>$roomid,'uuid'=>$uuid,'_logic'=>'OR'))->count()){
			$result['msg'] = "房间号或uuid已存在";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		if(!$ip) $ip = getClientIp();
		if(!$port) $port = '10000';
		$data = array('uuid'=>$uuid,'id'=>$roomid,'base_info'=>str_replace("&quot;", "\"", $base_info),'create_time'=>time(),'ip'=>$ip,'port'=>$port,'account'=>$account);
		$jxuser_id = '';
		if($is_join) {//1为创建并玩 0为是，说明只创建房间，不玩；
			if($userinfo['isjx']) {//是经销商且为创建并玩
//				$data['jxuser_id'] = $userid;
				$jxuser_id = $userid;
			}
//			$data['user_id0'] = $userid;
//			$data['user_icon0'] = $userinfo['headimgurl'];
//			$data['user_name0'] = $userinfo['nickname'];
		}else{//只创建房间，不玩
//			$data['jxuser_id'] = $userid;
			$jxuser_id = $userid;
		}
		if(!$m->add($data)){			
			$result['msg'] = "添加失败";
		}else{
			if($jxuser_id){
				$this->create_apply($jxuser_id, $uuid, $roomid, 0, $account);
			}
			$result['status'] = 1;
		}
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
	//指定房间经销商
	public function set_jxrooms(){
		$result = array('status'=>0);
		$userid = I("userid");
		$roomid = I("room_id");
		if(!$userid||!$roomid){
			$result['msg'] = "参数错误";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		$userinfo = $this->_get_user($openid,$userid);
		if(!$userinfo){
			$result['msg'] = "用户不存在";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}elseif (!$userinfo['status']){
			$result['msg'] = "用户被禁用";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}elseif(!$userinfo['isjx']){//不是经销商
			$result['msg'] = "用户不是经销商，不可指定房间";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		$m = M("rooms","t_");
		$roominfo = $m->where(array('id'=>$roomid))->find();
		if(!$roominfo){
			$result['msg'] = "房间不存在";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}elseif ($roominfo['jxuser_id']){
			$result['msg'] = "房间管理员已被指定";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		$res = $this->create_apply($userid, $roominfo['uuid'], $roominfo['id'],0,$roominfo['account']);
//		if(!$m->where(array('id'=>$roomid))->save(array('jxuser_id'=>$userid))){
		if($res==-1){
			$result['msg'] = "已申请过此房间";
		}elseif(!$res){
			$result['msg'] = "设置失败";
		}else{			
			$result['status'] = 1;
		}
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
	//添加申请房间经销商审核记录
	private function create_apply($userid,$uuid,$roomid,$status=0,$account=100,$date=''){
		$model = M("rooms_jx_apply","t_");
		if($model->where(array('room_uuid'=>$uuid,'room_id'=>$roomid,'jxuser_id'=>$userid))->count()){
			return -1;
		}
		if(!$date){
			$date = date("Y-m-d H:i:s");
		}
		$data = array('room_uuid'=>$uuid,'room_id'=>$roomid, 'jxuser_id'=>$userid, 'game_create_time'=>$date, 'create_time'=>$date);
		if($status>0){
			$data['jx_status'] = $status;
		}
		if($account>0){
			$data['account'] = $account;
		}
		return $model->add($data);
	}
	
	//获取结算明细
	public function get_account(){
		$result = array('status'=>0);
		$userid = I("userid");
		if(!$userid){
			$result['msg'] = "参数错误";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		$userinfo = $this->_get_user($openid,$userid);
		if(!$userinfo){
			$result['msg'] = "用户不存在";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}elseif (!$userinfo['status']){
			$result['msg'] = "用户被禁用";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}elseif(!$userinfo['isjx']){//不是经销商
			$result['msg'] = "用户不是经销商";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		$m = M("rooms_jx_apply","t_");
		$map = array('jxuser_id'=>$userid, 'jx_status'=>1, 'account_status'=>1);
		$offset=I("offset")?I("offset"):0;
		$limit=I("limit")?I("limit"):20;
		$data=$m->where($map)->limit($offset.",".$limit)->order("t_rooms_jx_apply.create_time DESC")->field("room_id,game_create_time create_time,account*0.01 account")->select();
		$result['status'] = 1;
		$result['data'] = $data?$data:array();
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
	//牌局结束更新结算状态
	public function game_account(){
		$result = array('status'=>0);
		$room_uuid = I("room_uuid");
		$end_time = I("end_time");
		if(!$room_uuid){
			$result['msg'] = "参数错误";
			$this->ajaxReturn($result, $this->AJAX_TYPE);
		}
		if(!$end_time){
			$end_time = date("Y-m-d H:i:s");
		}
		$m = M("rooms_jx_apply","t_");
		$re = $m->where(array('room_uuid'=>$room_uuid))->save(array('account_status'=>1,'game_end_time'=>$end_time));
		if($re){
			$result['status'] = 1;
		}else{
			$result['msg'] = "更新失败";
		}
		$this->ajaxReturn($result, $this->AJAX_TYPE);
	}
	
}